﻿using System;
using System.Collections;
using System.Drawing;
using System.Windows.Forms;
using StockHelper.Scripts;
using StockHelper.Scripts.Comm;
using StockHelper.Scripts.Sound;
using StockHelper.Scripts.Stock;
using StockHelper.Scripts.Types;

namespace StockHelper
{
    public partial class VoicePlay : Form
    {
        public static VoicePlay e;
        private Image itemImage;

        public VoicePlay()
        {
            InitializeComponent();
            e = this;
            SetStyle(ControlStyles.UserPaint, true);
            SetStyle(ControlStyles.AllPaintingInWmPaint, true); // 禁止擦除背景. 
            SetStyle(ControlStyles.DoubleBuffer, true); // 双缓冲
        }
        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams cp = base.CreateParams;
                cp.ExStyle |= 0x02000000;//用双缓冲绘制窗口的所有子控件
                return cp;
            }
        }

        private void VoicePlay_Load(object sender, EventArgs e)
        {
            this.BackgroundImage = Assets.LoadImg(Config.Get("bgImage", UI.bgImage));
            this.VolumeImage.Image = Assets.LoadImg(Config.Get("VoicePlay/VolumeImage", UI.VolumeImage));
            itemImage = Assets.LoadImg(UI.play_item);
            this.ui_bottom.BackgroundImage = Assets.LoadImg(UI.main_bottom);
            this.PlayBtn.BackgroundImage = Assets.LoadImg(UI.play_btn);
            this.AddVoice2Btn.BackgroundImage = this.AddVoiceBtn.BackgroundImage = Assets.LoadImg(UI.main_新增股票_btn);

            

            this.Volume.Value = (int)(Config.voiceVolume * 100);
            if (Config.playVoice)
                this.VoiceTimeBar.Text = Config.voiceTime + "秒";
            else
                this.VoiceTimeBar.Text = "不播报";
            
            Init();
        }


        public void Init()
        {
            this.ItemPanel.Controls.Clear();
            foreach (Hashtable table in Config.Get("voicePlay", new ArrayList()))
            {
                Panel panel = new Panel
                {
                    BackColor = Color.Transparent,
                    Width = 200,
                    Height = 100,
                    BackgroundImageLayout = ImageLayout.Zoom,
                    BackgroundImage = itemImage,
                    Cursor = Cursors.Hand,
                };
                panel.MouseClick += new MouseEventHandler((sender, e) =>
                {
                    Item_MouseClick(panel);
                });
                if (table.ContainsKey("isPrice") && table["isPrice"].ToString() == "1")
                {
                    Style.ExLabel label = new Style.ExLabel
                    {
                        Text = StockCtrl.GetData(table["url"].ToString(), Scripts.Types.Param.名称).ToString(),
                        BackColor = Color.Transparent,
                        Font = new Font("微软雅黑", 11),
                        ForeColor = Color.White,
                        Height = 40,
                        Dock = DockStyle.Top,
                        TextAlign = ContentAlignment.BottomCenter,
                        Cursor = Cursors.Hand,
                    };
                    panel.Controls.Add(label);
                    panel.MouseClick += new MouseEventHandler((sender, e) =>
                    {
                        Item_MouseClick(panel);
                    });
                    label = new Style.ExLabel
                    {
                        Text = table["key"].ToString(),
                        BackColor = Color.Transparent,
                        ForeColor = Color.White,
                        Font = new Font("微软雅黑", 11),
                        Dock = DockStyle.Bottom,
                        Height = 40,
                        TextAlign = ContentAlignment.TopCenter,
                        Cursor = Cursors.Hand,
                    };
                    label.MouseClick += new MouseEventHandler((sender, e) =>
                    {
                        Item_MouseClick(panel);
                    });
                    panel.Controls.Add(label);
                }
                else
                {
                    Style.ExLabel text = new Style.ExLabel
                    {
                        Dock = DockStyle.Fill,
                        TextAlign = ContentAlignment.MiddleCenter,
                        BackColor = Color.Transparent,
                        Font = new Font("微软雅黑", 11),
                        ForeColor = Color.White,
                        Text = table["name"].ToString(),
                        Cursor = Cursors.Hand,
                    };
                    text.MouseClick += new MouseEventHandler((sender, e) =>
                    {
                        Item_MouseClick(panel);
                    });
                    panel.Controls.Add(text);
                }
                this.ItemPanel.Controls.Add(panel);
            }

            ScrollBar_Init();
        }


        private Panel clickItem = null;

        public void Item_MouseClick(Panel item)
        {
            clickItem = item;
            this.ItemMenuStrip.Show(MousePosition);
            int index = this.ItemPanel.Controls.GetChildIndex(item);
            this.ItemMenuStrip.Items[0].Enabled = index != 0;
            this.ItemMenuStrip.Items[1].Enabled = index != this.ItemPanel.Controls.Count - 1;
        }


        private void AddVoiceBtn_Click(object sender, EventArgs e)
        {
            VoiceForm fm = new VoiceForm();
            fm.Show();

        }

        private void PlayBtn_Click(object sender, EventArgs e)
        {
            Sound.Stop();
            StockHelper.Scripts.Sound.VoicePlay.Play2();
        }

        private void backToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ChangeIndex(-1);
        }

        private void nextToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ChangeIndex(1);
        }

        private void delToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ChangeIndex(0);
        }

        private void ChangeIndex(int change)
        {
            int index = this.ItemPanel.Controls.GetChildIndex(clickItem);
            if (change == 0)
            {
                Config.Get("voicePlay", new ArrayList()).RemoveAt(index);
            }
            else
            {
                object obj = Config.Get("voicePlay", new ArrayList())[index];
                Config.Get("voicePlay", new ArrayList())[index] = Config.Get("voicePlay", new ArrayList())[index + change];
                Config.Get("voicePlay", new ArrayList())[index + change] = obj;
            }
            Init();
            Config.Save();
        }

        private void AddVoice2Btn_Click(object sender, EventArgs e)
        {
            VoiceForm fm = new VoiceForm(true);
            fm.Show();
        }

        private void VoiceTimeBar_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.VoiceTimeBar.Text == "不播报")
            {
                Config.playVoice = false;
                Config.Set("noPlayVoice", 1);
            }
            else
            {
                Config.playVoice = true;
                string result = System.Text.RegularExpressions.Regex.Replace(this.VoiceTimeBar.Text, @"[^0-9]+", "");
                Config.Set("voiceTime", Config.voiceTime = int.Parse(result));
                Scripts.Comm.Timer.Replace(StockHelper.Scripts.Sound.VoicePlay.Play, Time.GetTimeStamp() + Config.voiceTime, Config.voiceTime);
            }
        }

        private void VoiceTimeBar_KeyUp(object sender, KeyEventArgs e)
        {
            string result = System.Text.RegularExpressions.Regex.Replace(this.VoiceTimeBar.Text, @"[^0-9]+", "");
            this.VoiceTimeBar.Text = result;
        }

        private void VoiceTimeBar_Leave(object sender, EventArgs e)
        {
            if (this.VoiceTimeBar.Text == "不播报")
                return;
            string result = System.Text.RegularExpressions.Regex.Replace(this.VoiceTimeBar.Text, @"[^0-9]+", "");
            if (string.IsNullOrEmpty(result))
                this.VoiceTimeBar.SelectedIndex = 3;
            int.TryParse(result, out int i);
            if (i < 10)
                this.VoiceTimeBar.SelectedIndex = 3;
            else
            {
                Config.Set("voiceTime", Config.voiceTime = i);
                Scripts.Comm.Timer.Replace(StockHelper.Scripts.Sound.VoicePlay.Play, 0, Config.voiceTime);
            }
        }

        bool scrollBarInit = false;
        private void ScrollBar_Init()
        {
            if (this.ItemPanel.Height <= this.ItemPanelBox.Height)
            {
                this.ScrollBar.Visible = false;
                return;
            }
            this.ScrollBar.Visible = true;
            //滑块高度=可视高度/实际高度*滚动条高度（pn_scroll.Height）
            float length = (float)this.ItemPanelBox.Height / (float)this.ItemPanel.Height * (float)this.ScrollBar.Height;
            this.ScrollBar.SliderHeight = (int)length;

            if (!scrollBarInit)
            {
                this.ScrollBar.MouseDown += ScrollBar_MouseDown;
                this.ScrollBar.MouseUp += ScrollBar_MouseUp;
                this.ScrollBar.ValueChanged += ScrollBar_ValueChanged;  //滚动条拖动事件
                this.ScrollBar.GotFocus += ScrollBar_GotFocus;  //滚动条获得焦点事件
                this.ItemPanel.MouseWheel += ScrollBar_MouseWheel; //pn_info添加滚轮事件
            }
        }
        bool isMouseWheel = false; //防止滚轮带动的滚动条再次触发sb_ValueChanged
        //pn_info滚轮事件
        private void ScrollBar_MouseWheel(object sender, MouseEventArgs e)
        {
            isMouseWheel = true;
            int scrollRang = 40; //每次滚动高度(px)
            int sbRang = calSbRang(scrollRang); //滚动条实际滚动幅度
            if (e.Delta > 0) //滚轮向上
            {
                if (this.ScrollBar.Value - sbRang <= 0)
                {
                    //滚动到顶，直接设为默认值，防止滚动产生的误差
                    this.ScrollBar.Value = 0;
                    this.ItemPanel.Top = 0;
                }
                else
                {
                    this.ScrollBar.Value -= sbRang;
                    this.ItemPanel.Top += scrollRang;
                }
            }
            else//滚轮向下
            {
                if (this.ScrollBar.Value + sbRang >= 100)
                {
                    //滚动到底，直接设为默认值，防止滚动产生的误差
                    this.ScrollBar.Value = 100;
                    this.ItemPanel.Top = -(this.ItemPanel.Height - this.ItemPanelBox.Height);
                }
                else
                {
                    this.ScrollBar.Value += sbRang;
                    this.ItemPanel.Top -= scrollRang;
                }
            }

        }
        //因为滚动条滚动幅度可能是小数，转int后会损失精度，导致滚动到底或到底时产生一定误差
        float residue = 0; //float转int后舍去的小数部分累积凑1
        private int calSbRang(int scrollRang)
        {
            float temp = ((float)scrollRang) / (float)(this.ItemPanel.Height - this.ItemPanelBox.Height) * 100;//滚动条滚动比例
            int sbRang = Convert.ToInt32(temp);//保留整数部分
            residue += temp - (float)sbRang; //累积舍去的小数部分
            if (residue >= 1)
            {
                residue -= 1;
                sbRang += 1;
            }
            return sbRang;
        }

        //滚动条获取焦点时把焦点给pn_info,防止触发滚动条的滚轮事件(滚动条的滚轮滑动和容器内的滑动速度不一致)
        private void ScrollBar_GotFocus(object sender, EventArgs e)
        {
            isMouseWheel = false;
            this.ItemPanel.Focus();
        }
        //滚动条拖动
        private void ScrollBar_ValueChanged(object sender, EventArgs e)
        {
            if (!isMouseWheel ){
                this.ItemPanel.Top = -Convert.ToInt32((float)this.ScrollBar.Value / 100 * (float)(this.ItemPanel.Height - this.ItemPanelBox.Height));
            }
        }
        private void ScrollBar_MouseDown(object sender, MouseEventArgs e)
        {
            this.ItemPanelBox.BackColor = Color.Silver;
        }
        private void ScrollBar_MouseUp(object sender, MouseEventArgs e)
        {
            this.ItemPanelBox.BackColor = Color.Transparent;
        }

        private void Volume_ValueChanged(object sender, EventArgs e)
        {
            Config.voiceVolume = this.Volume.Value / 100f;
            Config.Save();
        }
    }
}